#ifndef SOCK_H
#define SOCK_H

#include <iostream>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>

class TCPSock
{
private:
public:
    TCPSock();

    static int Socket()
    {
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd == -1)
        {
            std::cerr << "Socket error" << std::endl;
            exit(2);
        }

        return sockfd;
    }

    static void Bind(int listen_sockfd, uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, sizeof local, 0);
        // bzero();
        local.sin_family = AF_INET;
        // 网络端口号大端
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(listen_sockfd, (struct sockaddr*)&local, sizeof local) == -1)
        {
            std::cerr << "Bind error" << std::endl;
            exit(3);
        }

        std::cout << "Bind success" << std::endl;
    }

    static void Listen(int listen_sockfd)
    {
const int backlog = 5;
        if(listen(listen_sockfd, backlog) == -1)
        {
            std::cerr << "Listen error" << std::endl;
            exit(4);
        }

        std::cout << "Listen success" << std::endl;
    }

    static int Accept(int listen_sockfd)
    {
        struct sockaddr_in peer;
        bzero(&peer, sizeof peer);
        socklen_t len = sizeof peer;
        int sockfd = accept(listen_sockfd, (struct sockaddr*)&peer, &len);
        if(sockfd == -1)
        {
            std::cerr << "Accept error" << std::endl;
            exit(5);
        }

        return sockfd;
    }

    static void Connect(int sockfd, std::string ip, uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, sizeof local, 0);
        if(connect(sockfd, (struct sockaddr*)&local, sizeof local) == -1)
        {
            std::cerr << "Connect error" << std::endl;
            exit(6);
        }

        std::cout << "Connect success" << std::endl;
    }

    ~TCPSock();
};

#endif